package com.cy.lib.image;

import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.view.View;

import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author CY
 * @title
 * @date 2015/7/28
 * @qq 568305883
 * @email tmxdyf@163.com
 */
public class ImageSave extends AsyncTask<Bitmap, Object, Object> implements ImageLoadingListener {

    File mSaveFile;
    OnSaveListener mListener;
    private final static ExecutorService mThreadPool = Executors.newCachedThreadPool();

    public ImageSave(File file, OnSaveListener listener) {
        mSaveFile = file;
        mListener = listener;
    }

    @Override
    public void onLoadingStarted(String imageUri, View view) {

    }

    @Override
    public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
        if (mListener != null) {
            mListener.error(mSaveFile);
        }
    }

    @Override
    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
        executeOnExecutor(mThreadPool, loadedImage);
    }

    @Override
    public void onLoadingCancelled(String imageUri, View view) {
    }

    @Override
    protected Object doInBackground(Bitmap... bitmaps) {
        try {
            if (!mSaveFile.exists()) {
                mSaveFile.createNewFile();
                if (!mSaveFile.getParentFile().exists()) {
                    mSaveFile.getParentFile().mkdirs();
                }
            }
            FileOutputStream fos = new FileOutputStream(mSaveFile);
            bitmaps[0].compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
            mSaveFile.delete();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Object o) {
        super.onPostExecute(o);

        if (mListener != null) {
            if (mSaveFile.exists()) mListener.finish(mSaveFile);
            else mListener.error(mSaveFile);
        }
    }

    public interface OnSaveListener {
        public void finish(File file);

        public void error(File file);
    }
}